<?php
namespace plugin\ky_shouyin\app\controller\admin;

use support\Request;
use support\Db;
use plugin\ky_shouyin\app\controller\BaseController;

class StatisticsController extends BaseController
{
    /**
     * 统计分析页面
     */
    public function index()
    {
        return $this->view('admin/statistics/index');
    }
    
    /**
     * 获取销售统计数据
     */
    public function sales(Request $request)
    {
        $type = $request->get('type', 'day');
        $dateRange = $request->get('date_range', '');
        
        try {
            if ($dateRange) {
                $dates = explode(' - ', $dateRange);
                $startDate = $dates[0];
                $endDate = $dates[1];
            } else {
                $startDate = date('Y-m-d', strtotime('-30 days'));
                $endDate = date('Y-m-d');
            }
            
            $query = Db::table('ky_order')
                ->where('status', 1)
                ->whereBetween('created_at', [
                    $startDate . ' 00:00:00',
                    $endDate . ' 23:59:59'
                ]);
                
            if ($type == 'day') {
                $groupBy = 'DATE(created_at)';
                $dateFormat = '%Y-%m-%d';
            } elseif ($type == 'month') {
                $groupBy = 'DATE_FORMAT(created_at, "%Y-%m")';
                $dateFormat = '%Y-%m';
            } else {
                $groupBy = 'YEAR(created_at)';
                $dateFormat = '%Y';
            }
            
            $stats = $query->selectRaw("
                DATE_FORMAT(created_at, '{$dateFormat}') as date,
                COUNT(*) as order_count,
                SUM(amount) as total_amount
            ")
            ->groupBy('date')
            ->orderBy('date', 'asc')
            ->get();
            
            $dates = [];
            $amounts = [];
            $orders = [];
            
            foreach ($stats as $item) {
                $dates[] = $item->date;
                $amounts[] = floatval($item->total_amount);
                $orders[] = intval($item->order_count);
            }
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => [
                    'dates' => $dates,
                    'amounts' => $amounts,
                    'orders' => $orders
                ]
            ]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '获取数据失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取会员统计数据
     */
    public function member()
    {
        try {
            // 会员等级分布
            $levels = Db::table('ky_member')
                ->leftJoin('ky_member_level', 'ky_member.level', '=', 'ky_member_level.id')
                ->selectRaw('
                    ky_member_level.name,
                    COUNT(*) as value
                ')
                ->groupBy('ky_member.level', 'ky_member_level.name')
                ->get();
                
            // 会员增长趋势
            $growth = Db::table('ky_member')
                ->selectRaw('
                    DATE(created_at) as date,
                    COUNT(*) as number
                ')
                ->where('created_at', '>=', date('Y-m-d', strtotime('-30 days')))
                ->groupBy('date')
                ->orderBy('date', 'asc')
                ->get();
                
            $dates = [];
            $numbers = [];
            
            foreach ($growth as $item) {
                $dates[] = $item->date;
                $numbers[] = intval($item->number);
            }
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => [
                    'levels' => $levels,
                    'growth' => [
                        'dates' => $dates,
                        'numbers' => $numbers
                    ]
                ]
            ]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '获取数据失败：' . $e->getMessage()]);
        }
    }
    
    /**
     * 获取支付方式统计数据
     */
    public function payment(Request $request)
    {
        $dateRange = $request->get('date_range', '');
        
        try {
            $query = Db::table('ky_order')->where('status', 1);
            
            if ($dateRange) {
                $dates = explode(' - ', $dateRange);
                $query->whereBetween('created_at', [
                    $dates[0] . ' 00:00:00',
                    $dates[1] . ' 23:59:59'
                ]);
            }
            
            $stats = $query->selectRaw('
                CASE 
                    WHEN payment_method = 1 THEN "现金"
                    WHEN payment_method = 2 THEN "微信"
                    WHEN payment_method = 3 THEN "支付宝"
                    ELSE "其他"
                END as name,
                COUNT(*) as value,
                SUM(amount) as amount
            ')
            ->groupBy('payment_method')
            ->get();
            
            return json([
                'code' => 0,
                'msg' => 'success',
                'data' => $stats
            ]);
        } catch (\Exception $e) {
            return json(['code' => 1, 'msg' => '获取数据失败：' . $e->getMessage()]);
        }
    }
} 